<template>
  <div>
    <a-alert message="注意：只允许为第三级分类设置相关参数！" banner />
    <div class="cascader">
      <a-row :gutter="2">
        <a-col :span="2">选择商品分类：</a-col>
        <a-col :span="6">
          <a-cascader
            :options="options"
            placeholder="请选择"
            @change="selectCascader"
            allowClear
            :field-names="{
              label: 'cat_name',
              value: 'cat_id',
              children: 'children',
            }"
          />
        </a-col>
      </a-row>
    </div>
    <!-- tabs切换栏 -->
    <div class="tabs">
      <a-tabs
        :default-active-key="activekey"
        :animated="false"
        @change="changeTabs"
      >
        <a-tab-pane key="many" tab="动态参数">
          <a-button type="primary" :disabled="isdiable" @click="addParamsModel">
            添加参数
          </a-button>
          <!-- 动态参数table表格 -->
          <div class="table">
            <a-table
              :columns="columns"
              :data-source="manyTableData"
              :pagination="false"
              :rowKey="
                (record, index) => {
                  return index;
                }
              "
            >
              <p slot="expandedRowRender" slot-scope="record" style="margin: 0">
                <a-tag
                  color="blue"
                  v-for="(item, index) in record.attr_vals"
                  :key="index"
                  closable
                  @close="closeTag(index, record)"
                  >{{ item }}</a-tag
                >
                <a-input
                  v-if="record.inputVisible"
                  ref="input"
                  type="text"
                  size="small"
                  :style="{ width: '78px' }"
                  :value="record.inputValue"
                  @change="handleInputChange"
                  @blur="handleInputConfirm(record)"
                  @keyup.enter="handleInputConfirm(record)"
                />
                <a-tag
                  v-else
                  style="background: #fff; borderstyle: dashed"
                  @click="showInput(record)"
                >
                  <a-icon type="plus" /> New Tag
                </a-tag>
              </p>
              <span slot="options" slot-scope="text, record">
                <a-row :gutter="1">
                  <a-col :span="4">
                    <a-button
                      type="primary"
                      icon="edit"
                      @click="editParamsModel(record)"
                    >
                      编辑
                    </a-button>
                  </a-col>
                  <a-col :span="4">
                    <a-popconfirm
                      title="你确定要删除吗?"
                      ok-text="是的"
                      cancel-text="再想想"
                      @confirm="deleteParams(record.attr_id)"
                    >
                      <a-button type="danger" icon="delete"> 删除 </a-button>
                    </a-popconfirm>
                  </a-col>
                </a-row>
              </span>
            </a-table>
          </div>
        </a-tab-pane>
        <a-tab-pane key="only" tab="静态属性" force-render>
          <a-button type="primary" :disabled="isdiable" @click="addParamsModel">
            添加属性
          </a-button>
          <!-- 静态属性table表格 -->
          <div class="table">
            <a-table
              :columns="columns"
              :data-source="onlyTableData"
              :pagination="false"
              :rowKey="
                (record, index) => {
                  return index;
                }
              "
            >
              <p slot="expandedRowRender" slot-scope="record" style="margin: 0">
                <a-tag
                  color="blue"
                  v-for="(item, index) in record.attr_vals"
                  :key="index"
                  closable
                  @click="closeTag(index, record)"
                  >{{ item }}</a-tag
                >
                <a-input
                  v-if="record.inputVisible"
                  ref="input"
                  type="text"
                  size="small"
                  :style="{ width: '78px' }"
                  :value="record.inputValue"
                  @change="handleInputChange"
                  @blur="handleInputConfirm(record)"
                  @keyup.enter="handleInputConfirm(record)"
                />
                <a-tag
                  v-else
                  style="background: #fff; borderstyle: dashed"
                  @click="showInput(record)"
                >
                  <a-icon type="plus" /> New Tag
                </a-tag>
              </p>
              <span slot="options" slot-scope="text, record">
                <a-row :gutter="1">
                  <a-col :span="4">
                    <a-button
                      type="primary"
                      icon="edit"
                      @click="editParamsModel(record)"
                    >
                      编辑
                    </a-button>
                  </a-col>
                  <a-col :span="4">
                    <a-popconfirm
                      title="你确定要删除吗?"
                      ok-text="是的"
                      cancel-text="再想想"
                      @confirm="deleteParams(record.attr_id)"
                    >
                      <a-button type="danger" icon="delete"> 删除 </a-button>
                    </a-popconfirm>
                  </a-col>
                </a-row>
              </span>
            </a-table>
          </div>
        </a-tab-pane>
      </a-tabs>
    </div>
    <!-- 添加动态/静态属性参数对话框 -->
    <div class="addmodel">
      <a-modal
        :title="`添加${getModelTitleText}`"
        :visible="isAddParamsModel"
        @ok="addParams"
        @cancel="cancelAddParams"
        cancelText="取消"
        okText="确定"
      >
        <a-form
          :form="form"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 12 }"
        >
          <a-form-item :label="`${getModelTitleText}名称`">
            <a-input
              v-decorator="[
                'attr_name',
                {
                  rules: [
                    {
                      required: true,
                      message: `请输入你的${getModelTitleText}名称`,
                    },
                  ],
                },
              ]"
              :placeholder="`请输入你的${getModelTitleText}名称`"
            />
          </a-form-item>
        </a-form>
      </a-modal>
    </div>
    <!-- 修改动态/静态属性参数对话框 -->
    <div class="editmodel">
      <a-modal
        :title="`修改${getModelTitleText}`"
        :visible="iseditParamsModel"
        @ok="editParams"
        @cancel="iseditParamsModel = false"
        cancelText="取消"
        okText="确定"
      >
        <a-form
          :form="form"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 12 }"
        >
          <a-form-item :label="`${getModelTitleText}名称`">
            <a-input
              v-decorator="[
                'attr_name',
                {
                  rules: [
                    {
                      required: true,
                      message: `请输入你的${getModelTitleText}名称`,
                    },
                  ],
                },
              ]"
              :placeholder="`请输入你的${getModelTitleText}名称`"
            />
          </a-form-item>
        </a-form>
      </a-modal>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      options: [],
      //级联选择器选中的数组
      cascader: [],
      manyTableData: [],
      onlyTableData: [],
      columns: [
        {
          title: "参数名称",
          dataIndex: "attr_name",
          key: "attr_name",
          width: "50%",
        },
        {
          title: "操作",
          dataIndex: "options",
          key: "options",
          scopedSlots: { customRender: "options" },
        },
      ],
      data: [],
      activekey: "many",
      //添加模态框
      isAddParamsModel: false,
      //修改模态框
      iseditParamsModel: false,
      editParamsItem: "",
      form: this.$form.createForm(this, { name: "dynamic_rule" }),
      inputVisible: false,
      inputValue: "",
      InputValueTest: "",
    };
  },
  created() {
    this.getParentCateList();
  },
  computed: {
    //是否禁用btn按钮
    isdiable() {
      if (this.cascader.length >= 3) {
        return false;
      } else {
        return true;
      }
    },
    //获取选择类别的id
    getCateId() {
      if (this.cascader.length >= 3) {
        return this.cascader[2];
      } else {
        return null;
      }
    },
    //获取模态框的文本
    getModelTitleText() {
      if (this.activekey === "many") {
        return "动态参数";
      }
      return "静态属性";
    },
  },
  methods: {
    //获取所有父级商品分类
    async getParentCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: {
          type: 3,
        },
      });
      if (res.meta.status !== 200) {
        return this.$message.info(res.meta.msg);
      }
      this.options = res.data;
    },
    //改变级联选择器事件
    selectCascader(event) {
      if (event.length >= 3) {
        this.cascader = event;
        this.getTableList();
      } else {
        this.cascader = [];
        this.onlyTableData = [];
        this.manyTableData = [];
      }
    },
    //修改tabs面板
    changeTabs(sel) {
      this.activekey = sel;
      this.getTableList();
    },
    //获取表格数据
    async getTableList() {
      if (this.cascader.length >= 3) {
        const { data: res } = await this.$http.get(
          `categories/${this.getCateId}/attributes`,
          {
            params: { sel: this.activekey },
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("获取参数列表失败！");
        }
        res.data.forEach((item) => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
          item.inputVisible = false;
          item.inputValue = "";
        });
        if (this.activekey === "many") {
          this.$nextTick(() => {
            this.manyTableData = res.data;
          });
        }
        if (this.activekey === "only") {
          this.$nextTick(() => {
            this.onlyTableData = res.data;
          });
        }
      }
    },
    //弹出添加参数模态框
    addParamsModel() {
      this.isAddParamsModel = true;
    },
    //取消添加参数
    cancelAddParams() {
      this.isAddParamsModel = false;
      this.form.resetFields();
    },
    //添加参数
    addParams() {
      this.form.validateFields(async (err) => {
        if (!err) {
          const { data: res } = await this.$http.post(
            `categories/${this.getCateId}/attributes`,
            {
              attr_name: this.form.getFieldValue("attr_name"),
              attr_sel: this.activekey,
            }
          );
          if (res.meta.status !== 201) {
            return this.$message.info(res.meta.msg);
          }
          this.getTableList();
          this.isAddParamsModel = false;
          this.$message.success(res.meta.msg);
        }
      });
    },
    //修改模态框碳库
    editParamsModel(params) {
      this.iseditParamsModel = true;
      this.editParamsItem = params;
      this.$nextTick(() => {
        this.form.setFieldsValue({
          attr_name: params.attr_name,
        });
      });
    },
    //修改参数
    editParams() {
      this.form.validateFields(async (err) => {
        if (!err) {
          const { data: res } = await this.$http.put(
            `categories/${this.getCateId}/attributes/${this.editParamsItem.attr_id}`,
            {
              attr_name: this.form.getFieldValue("attr_name"),
              attr_sel: this.activekey,
            }
          );
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg);
          }
          this.getTableList();
          this.iseditParamsModel = false;
          this.$message.success(res.meta.msg);
        }
      });
    },
    //删除参数
    async deleteParams(attrId) {
      const { data: res } = await this.$http.delete(
        `categories/${this.getCateId}/attributes/${attrId}`
      );
      if (res.meta.status !== 200) {
        return this.$message.info(res.meta.msg);
      }
      this.getTableList();
      this.$message.success(res.meta.msg);
    },
    //显示input框
    showInput(row) {
      row.inputVisible = true;
      this.$nextTick(function () {
        this.$refs.input.focus();
      });
    },
    //input内的值
    handleInputChange(e) {
      this.InputValueTest = e.target.value;
    },
    //失去焦点或按下enter都会触发
    async handleInputConfirm(row) {
      //输入不合法数据
      if (this.InputValueTest.trim().length === 0) {
        row.inputVisible = false;
        row.inputValue = "";
        return false;
      }
      row.attr_vals.push(this.InputValueTest);
      this.InputValueTest = "";
      this.changeParms(row);
    },
    async changeParms(row) {
      //发起ajax请求
      const { data: res } = await this.$http.put(
        `categories/${this.getCateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(" "),
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.info(res.meta.msg);
      }
    },
    //删除参数
    closeTag(index, row) {
      row.attr_vals.splice(index, 1);
      this.changeParms(row);
    },
  },
};
</script>

<style lang="less" scoped>
.cascader {
  margin-top: 30px;
  margin-bottom: 30px;
}
.ant-cascader-picker {
  width: 100%;
}
</style>
